import axios from 'axios'
import { message } from 'ant-design-vue'
import Data from '@/utils/data'

const showMessage = msg => {
	message.error(msg)
}

const errorHandle = (status, message) => {
	if (message.includes('invalid_token')) {
		// token 错误清除token
		Data.setToken(null)
		window.location.href = window.location.href.split('#')[0] + '#/login'
	}
	if (message.includes('验证码错误')) {
		return
	}
	if (message.includes('敏感词')) {
		return
	}
	showMessage(message)
}

var instance = axios.create({ timeout: 1000 * 15 })
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

instance.interceptors.request.use(
	config => {
		return config
	},
	error => Promise.error(error)
)

instance.interceptors.response.use(
	res => {
		let api = ''
		let request = {
			url: res?.config?.url,
			param: res?.config?.data,
			response: res?.data,
		}
		try {
			api = request.url.split('/').slice(3).join('/')
			request.param = JSON.parse(request.param)
		} catch (error) {}
		if (res.status === 200) {
			if (res.headers['content-type'] === 'application/vnd.ms-excel;charset=UTF-8') {
				return res.data
			} else if (res.data.code === 20000) {
				return res.data?.data || {}
			} else if (res.data.code === 0) {
				return res.data.data
			} else {
				errorHandle(res.data.code, res.data.message)
				console.log(`%c FALIURE: ${api}`, 'color:#FF6A3F;background:#f658511f;', request)
				return Promise.reject(res)
			}
		} else {
			Promise.reject(res)
		}
	},
	error => {
		console.log('error:', error)
		const { response } = error
		if (response) {
			errorHandle(response.status, response.data.message)
			return Promise.reject(response)
		} else {
			errorHandle('other', error.toString())
			if (window.navigator.onLine) {
				return Promise.reject(error)
			}
		}
	}
)

export default instance
